<template>
  <van-nav-bar :title="clazzName + '班第' + week + '周课堂'" fixed safe-area-inset-top />
  <div>
    <h1>{{ clazzName }}第{{ week }}周班考勤列表</h1>

    <van-list>

      <van-cell v-for="att in attendList" :key="att.schedule.id">
        <van-row @click="toggleAttendanceView(att, currentStudent)">
          <AttendanceBar :attendance="att" :student="currentStudent" @handle="handle" />
        </van-row>
        <TuneAttendanceView v-if="att.details" :attendance="att" :student="currentStudent" @handle="handle" />
      </van-cell>
    </van-list>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { inject } from 'vue';
import service from '@/api';
import AttendanceBar from '@/components/AttendanceBar.vue';
import TuneAttendanceView from '@/components/TuneAttendanceView.vue';
const currentStudent = inject("currentStudent");
const { week, day } = inject('currentTime');

const clazzId = currentStudent.clazzId;

const clazzName = ref('');
const pendingAttendanceList = ref([]);
const completedAttendanceList = ref([]);
const attendList = ref([]);

const fetchData = async () => {
  const clazz = await service.get(`/api/clazz/${clazzId}`, null, "获取班级信息");
  clazzName.value = clazz.name;

  const attendanceList = await service.get(`/api/attendance/week/${week}/clazz/${clazzId}`, null, "获取考勤列表");
  const courseScheduleList = await service.get(`/api/courses_schedule/week/${week}/clazz/${clazzId}`, null, "获取课程安排");

  // 创建已考勤课程列表
  completedAttendanceList.value = attendanceList.map(attendance => ({
    id: attendance.id,
    state: attendance.state,
    courseScheduleId: attendance.courseScheduleId
  })).map(attendance => ({
    ...attendance, schedule: courseScheduleList.find(item => item.id == attendance.courseScheduleId)
  })
  );


  // 去掉已经考勤的课程
  const pendingScheduleList = courseScheduleList.filter(item => attendanceList.findIndex(att => att.courseScheduleId == item.id) < 0);

  // 创建待考勤课程列表
  pendingAttendanceList.value = pendingScheduleList.map(course => ({
    id: null, state: '未开始',
    schedule: {
      id: course.id,
      courseName: course.courseName,
      day: course.day,
      week: course.week,
      startPeriod: course.startPeriod,
      endPeriod: course.endPeriod
    }
  }));
  let attlist = completedAttendanceList.value.concat(pendingAttendanceList.value);
  //排序
  attlist = attlist.sort((a, b) => {
    return 100 * (a.schedule.startPeriod - b.schedule.startPeriod) + (a.schedule.endPeriod - b.schedule.endPeriod);
  });
  //给定当前学生在这堂课考勤的状态
  const attendDetailStatusOfGivenStudentObject = await service.get(`/api/attendance/detailstatus/${currentStudent.id}`, null, "获取学生的全部考勤详情");
  attlist = attlist.map(att => ({
    ...att,
    detailStatus: attendDetailStatusOfGivenStudentObject[att.id] || null
  }));

  attendList.value = attlist
};

const startAttendance = async (courseScheduleId) => {
  await service.post(`/api/attendance/start/${courseScheduleId}`, null, "开启考勤");
  fetchData();
};
const checkAttendance = async (attendanceId, studentId) => {
  await service.post(`/api/attendance/check/${attendanceId}/${studentId}`, null, "签到");
  fetchData();
};



const handle = async (type, attendance, student) => {
  if (type == 'start') {
    await startAttendance(attendance.schedule.id);
  } else if (type == 'check') {
    await checkAttendance(attendance.id, student.id);
  } else if (type == 'tune') {
    await tuneAttendance(attendance, student);
  } else if (type == 'lock') {
    await lockAttendance(attendance.id, student.id);
  } else if (type == 'submit') {
    await submitAttendance(attendance.id, student.id);
  }
};


const tuneAttendance = async (attendance, student) => {

  const details = attendance.details.reduce((accumulator, currentValue) => {
    accumulator.push({ studentId: currentValue.studentId, status: currentValue.status });
    return accumulator;
  }, []);
  const attend = await service.post(`/api/attendance/tune/${attendance.id}/${currentStudent.id}`, details, "获取考勤详情");

};

const lockAttendance = async (attendanceId, studentId) => {
  await service.post(`/api/attendance/lock/${attendanceId}/${studentId}`, null, "锁定考勤");
  fetchData();
};

const submitAttendance = async (attendanceId, studentId) => {
  await service.post(`/api/attendance/submit/${attendanceId}/${studentId}`, null, "提交考勤");
  fetchData();
};

/**
 * 展示考勤明细面板
 * @param {*} attendance 
 * @param {*} student 
 */
const toggleAttendanceView = async (attendance, student) => {
  if (currentStudent.isAdmin) {
    if (attendance.details) {
      attendance.details = null;
    } else {
      const attend = await service.get(`/api/attendance/${attendance.id}/details`, null, "获取考勤详情");
      const att = attendList.value.find(item => item.id == attendance.id);
      att.details = attend.details;
    }
  }

}
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
h1 {
  margin-bottom: 20px;
}

.van-list {
  margin-bottom: 20px;
}
</style>